import { IState } from "../interface/IState";
import { StateBase } from "./StateBase";

/**
 * 状态机一般基类
 */
export class State extends StateBase {
    private onEnterFunc: (state: State, prevState: IState, param?: any) => void;
    private onUpdateFunc: (state: State, dt: number) => void;
    private onExitFunc: (state: State, nextState: IState, param?: any) => void;
    private canExitFunc: (state: State) => boolean

    /**
     * 构造
     * @param onEnter - 进入状态回调
     * @param onUpdate - 状态执行回调
     * @param onExit - 状态退出回调
     * @param canExit - 是否能退出的函数
     * @param needExitTime - 是否需要等待回调
     */
    constructor(
        onEnter: (state: State, prevState: IState, param?: any) => void = null,
        onUpdate: (state: State, dt: number) => void = null,
        onExit: (state: State, nextState: IState, param?: any) => void = null,
        canExit: (state: State) => boolean = null,
        needExitTime = false
    ) {
        super();
        this.needExitTime = needExitTime
        this.onEnterFunc = onEnter;
        this.onUpdateFunc = onUpdate;
        this.onExitFunc = onExit;
        this.canExitFunc = canExit;
    }


    onEnter(prevState: IState, param?: any): void {
        super.onEnter(prevState, param)
        if (this.onEnterFunc) this.onEnterFunc(this, prevState, param)
    }

    onExit(nextState: IState, param?: any): void {
        super.onExit(nextState, param)
        if (this.onExitFunc) this.onExitFunc(this, nextState, param)
    }

    onUpdate(dt: any) {
        super.onUpdate(dt)
        if (this.onUpdateFunc) this.onUpdateFunc(this, dt)
    }


    requestExit() {
        if (!this.needExitTime || (this.canExitFunc && this.canExitFunc(this))) {
            this.fsm.stateCanExit()
        }
    }
}